#!/usr/bin/env python3
import pika
import time
import json
from subprocess import Popen, PIPE
import sqlite3
import sys
import socket
import loger
import os

os.chdir("/home/aiot/workspace/EpidemicPreventionProj/EP_faceDbManager")


def sendFaceDbOperateMsg(udpmsg):
    # 建立连接
    credentials = pika.PlainCredentials('aiot', 'aiot')
    Parameter = pika.ConnectionParameters('127.0.0.1', 5672, '/', credentials)
    connection = pika.BlockingConnection(Parameter)
    channel = connection.channel()

    # 声明/指定消息队列
    channel.queue_declare(queue='PDMoutQueue')

    channel.basic_publish(exchange='',
                          routing_key='PDMoutQueue',
                          body=udpmsg)
    log.info("[x] Sent msg out to PDMoutQueue!")
    log.info("sent out msg: " + str(udpmsg))


def sendOpenDoorStatusMsg(udpmsg):
    # 建立连接
    credentials = pika.PlainCredentials('aiot', 'aiot')
    Parameter = pika.ConnectionParameters('127.0.0.1', 5672, '/', credentials)
    connection = pika.BlockingConnection(Parameter)
    channel = connection.channel()

    # 声明/指定消息队列
    channel.queue_declare(queue='ShowDoorOpenStatusQueue')

    msgcontext = str(udpmsg).split("msg")[1]
    msgcontext.replace(":", "")
    msgcontext.replace("}", "")
    msgcontext.replace("(", "")
    msgcontext.replace(")", "")

    channel.basic_publish(exchange='',
                          routing_key='ShowDoorOpenStatusQueue',
                          body=msgcontext)
    log.info(" [x] Sent msg out to ShowDoorOpenStatusQueue!")
    log.info("sent out msg: " + str(msgcontext))


if __name__ == '__main__':
    '''
    发布img imgpath指令至rabbitMQ服务器
    '''
    log = loger.Log("udp2mqqueue_server")

    # udp socket
    BUFSIZE = 1024
    server = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    #ip_port = ('10.39.245.15', 9998)
    ip_port = ('127.0.0.1', 9998)
    server.bind(ip_port)

    # udp server
    while True:
        data, client_addr = server.recvfrom(BUFSIZE)
        log.info('from PassDB manager get: ' + str(data))

        if "msg" in str(data):
            # 生成用于显示开门状态的消息，发布消息
            print("AAAAAAAAAAAAAAAAAAAAAAAAAA: ", data)
            log.info("AAAAAAAAAAAAAAAAAAAAAAAAAA: " + str(data))
            sendOpenDoorStatusMsg(data)
        else:
            # 生成调用db操作指令消息内容,发布消息
            print("BBBBBBBBBBBBBBBBBBBBBBBBB: ", data)
            log.info("BBBBBBBBBBBBBBBBBBBBBBBBB: " + str(data))
            sendFaceDbOperateMsg(data)

    server.close()
